<template>
  <div class="blogs-container">
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="博客列表" name="blogs">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>博客管理</span>
              <el-button type="primary" :icon="Plus" @click="handleCreate">
                新增博客
              </el-button>
            </div>
          </template>
      
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入标题"
            clearable
            style="width: 180px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.category_id"
            placeholder="请选择分类"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="searchForm.tag_id"
            placeholder="请选择标签"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
            <el-option label="全部" :value="undefined" />
            <el-option label="已发布" :value="1" />
            <el-option label="草稿" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 博客列表表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categories" label="分类" width="150">
          <template #default="{ row }">
            <div v-if="row.categories && row.categories.length > 0" class="category-tags">
              <el-tag
                v-for="category in row.categories"
                :key="category.id"
                type="info"
                size="small"
                effect="plain"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ category.name }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签" min-width="200">
          <template #default="{ row }">
            <div v-if="row.tags && row.tags.length > 0" class="tag-list">
              <el-tag
                v-for="tag in row.tags"
                :key="tag.id"
                :style="{ color: tag.color || undefined, borderColor: tag.color || undefined }"
                type="primary"
                size="small"
                effect="plain"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ tag.name }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="summary" label="摘要" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status === 0"
              link
              type="success"
              size="small"
              @click="handlePublish(row)"
            >
              发布
            </el-button>
            <el-button
              v-else
              link
              type="warning"
              size="small"
              @click="handleUnpublish(row)"
            >
              取消发布
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
        </el-card>
        
        <!-- 博客编辑对话框 -->
        <BlogDialog
          v-model="dialogVisible"
          :blog-id="currentBlogId"
          @success="handleDialogSuccess"
        />
      </el-tab-pane>
      
      <el-tab-pane label="标签管理" name="tags">
        <TagsManagement />
      </el-tab-pane>
      
      <el-tab-pane label="分类管理" name="categories">
        <CategoriesManagement />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getBlogList, deleteBlog, publishBlog, unpublishBlog } from '@/api/blogs'
import { getCategoryList } from '@/api/categories'
import { getTagList } from '@/api/tags'
import BlogDialog from '@/components/BlogDialog.vue'
import TagsManagement from '@/components/TagsManagement.vue'
import CategoriesManagement from '@/components/CategoriesManagement.vue'
import { formatDateTime } from '@/utils'

interface Category {
  id: string
  name: string
  description?: string
  sort_order?: number
  created_at?: string
  updated_at?: string
}

interface Tag {
  id: string
  name: string
  color?: string
  description?: string
  created_at?: string
  updated_at?: string
}

interface Blog {
  id: string
  title: string
  content: string
  summary?: string
  cover?: string
  status?: number
  categories?: Category[]
  tags?: Tag[]
  created_at?: string
  updated_at?: string
  [key: string]: any
}

interface SearchForm {
  title: string
  category_id: string
  tag_id: string
  status: number | undefined
}

interface Pagination {
  page: number
  pageSize: number
  total: number
}

const router = useRouter()
const route = useRoute()

// 从路由查询参数获取当前tab，如果没有则使用默认值
const activeTab = ref<string>((route.query.tab as string) || 'blogs')
const loading = ref(false)
const tableData = ref<Blog[]>([])
const dialogVisible = ref(false)
const currentBlogId = ref<string | null>(null)

const searchForm = reactive<SearchForm>({
  title: '',
  category_id: '',
  tag_id: '',
  status: undefined
})

const categoryOptions = ref<Category[]>([])
const tagOptions = ref<Tag[]>([])

const pagination = reactive<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0
})

// 获取分类列表（用于搜索下拉框）
const fetchCategoryOptions = async (): Promise<void> => {
  try {
    const res = await getCategoryList({ pageSize: 100 })
    if (res.code === 200 && res.data) {
      categoryOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取标签列表（用于搜索下拉框）
const fetchTagOptions = async (): Promise<void> => {
  try {
    const res = await getTagList({ pageSize: 100 })
    if (res.code === 200 && res.data) {
      tagOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 获取博客列表
const fetchBlogList = async (): Promise<void> => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await getBlogList(params)
    if (res.code === 200 && res.data) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    console.error('获取博客列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (): void => {
  pagination.page = 1
  fetchBlogList()
}

// 重置搜索
const handleReset = (): void => {
  searchForm.title = ''
  searchForm.category_id = ''
  searchForm.tag_id = ''
  searchForm.status = undefined
  pagination.page = 1
  fetchBlogList()
}

// 新增博客
const handleCreate = (): void => {
  currentBlogId.value = null
  dialogVisible.value = true
}

// 编辑博客
const handleEdit = (row: Blog): void => {
  currentBlogId.value = row.id
  dialogVisible.value = true
}

// 查看博客详情
const handleView = (row: Blog): void => {
  router.push({ name: 'BlogDetail', params: { id: row.id } })
}

// 发布博客
const handlePublish = async (row: Blog): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      `确定要发布博客 "${row.title}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await publishBlog({ id: row.id })
    ElMessage.success('发布成功')
    fetchBlogList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布博客失败:', error)
    }
  }
}

// 取消发布博客
const handleUnpublish = async (row: Blog): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      `确定要取消发布博客 "${row.title}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await unpublishBlog({ id: row.id })
    ElMessage.success('已取消发布')
    fetchBlogList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消发布博客失败:', error)
    }
  }
}

// 删除博客
const handleDelete = async (row: Blog): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      `确定要删除博客 "${row.title}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteBlog({ id: row.id })
    ElMessage.success('删除成功')
    fetchBlogList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除博客失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number): void => {
  pagination.pageSize = size
  pagination.page = 1
  fetchBlogList()
}

// 页码改变
const handlePageChange = (page: number): void => {
  pagination.page = page
  fetchBlogList()
}

// 对话框操作成功
const handleDialogSuccess = (): void => {
  fetchBlogList()
}

// 处理编辑跳转
const handleEditFromQuery = (): void => {
  const editId = route.query.edit
  if (editId && typeof editId === 'string') {
    currentBlogId.value = editId
    dialogVisible.value = true
    // 清除 edit 查询参数，但保留 tab 参数
    const query: Record<string, any> = {}
    if (route.query.tab) {
      query.tab = route.query.tab
    }
    router.replace({ name: 'Blogs', query })
  }
}

// 监听路由参数，处理编辑跳转
watch(() => route.query.edit, () => {
  handleEditFromQuery()
}, { immediate: true })

// 监听 activeTab 变化，同步更新路由查询参数
watch(activeTab, (newTab: string) => {
  if (route.query.tab !== newTab) {
    router.replace({
      name: 'Blogs',
      query: {
        ...route.query,
        tab: newTab
      }
    })
  }
})

// 监听路由查询参数变化，同步更新 activeTab
watch(
  () => route.query.tab,
  (newTab: any) => {
    if (newTab && typeof newTab === 'string' && newTab !== activeTab.value) {
      activeTab.value = newTab
    }
  }
)

onMounted((): void => {
  fetchCategoryOptions()
  fetchTagOptions()
  fetchBlogList()
  handleEditFromQuery()
})
</script>

<style lang="scss" scoped>
.blogs-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .category-tags,
  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }
}
</style>

